<template>
  <el-dialog
    @close="closeDialog"
    v-model="dialogVisible"
    title="审核"
    width="600px"
  >

  <div class="auditWrap">
    <el-radio-group size="large" @chagne=""  v-model="auditState" style="margin-bottom: 30px,">
    <el-radio-button value="2" label="2"> 通过申请 </el-radio-button>
    <el-radio-button value="3" label="3"> 拒绝申请 </el-radio-button>
  </el-radio-group>
  </div>

    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
    <el-form-item v-if="auditState=='2'" label="申请单位">
       <span>{{ data?.enterpriseName }}</span>
      </el-form-item>
      <el-row>
        <el-col :span="14">
          <el-form-item v-if="auditState=='2'" label="培训时间" prop="date">
        <el-select
          v-model="formData.date"
          style="width: 100%;"
          placeholder="日期"
        >
          <el-option
            :value="item.value"
            :label="item.label" 
            v-for="item in dateList"
            :key="item.label"
          ></el-option>
        </el-select>
        
      </el-form-item>
      
        </el-col>
        <el-col :span="9" :offset="1">

          <el-form-item label-width="0" v-if="auditState=='2'" label="" prop="time">
        <el-select
          v-model="formData.time"
          style="width: 100%"
          placeholder="时间"
        >
          <el-option
            :value="item.value"
            :label="item.label" 
            v-for="item in timeList"
            :key="item.label"
            
          ></el-option>
        </el-select>
      </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-form-item v-if="auditState=='2'" label="培训主讲人" prop="leturerName">
        <el-select
          v-model="formData.leturerName"
          filterable
          placeholder="请选择"
          style="width: 240px"
        >
          <el-option
              v-for="item in userList"
              :key="item.userName"
              :label="item.userName+' '+item.mobile"
              :value="item.userName"
            />
          </el-select>
      </el-form-item> -->

      <!-- <el-form-item v-if="auditState=='3'" label="拒绝原因" prop="auditReason">
        <el-input
        type="textarea"
          v-model="formData.auditReason"
          :disabled="isDisabled"
        />
      </el-form-item> -->

      <el-form-item  label="审核意见" prop="auditReason">
        <el-input
        type="textarea"
          v-model="formData.auditReason"
          :disabled="isDisabled"
        />
      </el-form-item>
      
    </el-form>
    <div class="footer">
      <!-- <el-button @click="closeDialog">拒绝申请</el-button> -->
      <el-button @click="closeDialog">取消</el-button>
      <el-button
        v-if="!isDisabled"
        @click="submitForm(ruleFormRef)"
        type="primary"
        :loading="submitLoading"
      >
        提交
      </el-button>
      
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, onActivated, onMounted, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules, UploadProps, dayjs } from "element-plus";
import { baseURL } from "@/util/request";
import { ApiResult } from "@/util/request";
import { addVideo, selectVideoList, updateVideo } from "@/api/videoManage.ts";
import { audit, selectMiniTranUsers } from "@/api/apply";

interface IForm {
  id: string;
  videoName: string;
  videoFileUrl: string;
  videoFileId: string;
  videoTypeIds: [];

  auditReason:string;
  leturer:string,
  leturerName:string,
  date:string,
  time:string,
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: () => {},
  },
  isDisabled: {
    type: Boolean,
    default: false,
  },
  parentMenuOption: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:visible", "update:data", "submit"]);

const ruleFormRef = ref();
const uploadRef = ref();
const videoTypeList = ref<any[]>([]);
const dateList = ref<any[]>([]);
const timeList = ref<any[]>([]);
const userList = ref<any[]>([]);
const auditState = ref<string>("2");
  
const submitLoading = ref<boolean>(false);
const xAuthToken = ref<string>(localStorage.getItem("x-auth-token"));

const formData = reactive<IForm>({
  id: "",
  videoName: "",
  videoFileUrl: "",
  videoFileId: "",
  videoTypeIds: [],

  auditReason:"",
  leturer:"",
  leturerName:"",
  date:"",
  time:"",
});

let btnLoading = ref<boolean>(false);
let playerOptions = ref({
  // height: 200,
  // width: document.documentElement.clientWidth, //播放器宽度
  playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
  autoplay: false, // 如果true,浏览器准备好时开始回放。
  muted: true, // 默认情况下将会消除任何音频。
  loop: true, // 导致视频一结束就重新开始。
  preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
  language: "zh-CN",
  aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
  fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
  notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
  controls: true,
  controlBar: {
    timeDivider: true,
    durationDisplay: true,
    remainingTimeDisplay: false,
    fullscreenToggle: true, // 全屏按钮
  },
});

//TODO 做成动态
const rules = reactive<FormRules<IForm>>({
  leturer: [{ required: true, message: "请输入", trigger: "blur" }],
  auditReason: [{ required: false, message: "请输入", trigger: "blur" }],
  
  // videoFileUrl: [{ required: true, message: "请上传", trigger: "change" }],
  date: [{ required: true, message: "请选择", trigger: "change" }],
  time: [{ required: true, message: "请选择", trigger: "change" }],
  leturerName: [{ required: true, message: "请选择", trigger: "change" }],
  
});

const dialogVisible = computed({
  get() {
    return props.visible;
  },

  set(visible: boolean) {
    emit("update:visible", visible);
  },
});

//TODO 做成动态
const title = computed(() => {
  return props?.data?.id ? (props?.isDisabled ? "详情" : "编辑") : "新增";
});

function clearUploadFile() {
  uploadRef.value?.clearFiles();
}

function onUploadSuccess(response: any) {
  if (response?.code === 500) {
    ElMessage.error(response?.msg || "上传错误！");
    clearUploadFile();
    return;
  }
  formData.videoFileUrl = response?.data?.fileUrl;
  formData.videoFileId = response?.data?.id;
  btnLoading.value = false;
  ElMessage.success("上传完成！");
}
function onProgress() {
  btnLoading.value = true;
}
function closeDialog() {
  resetForm(ruleFormRef.value);
  emit("update:visible", false);
  emit("update:data", null);
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

async function getSelectVideoList() {
  const { success, msg, data } = await selectVideoList();
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  videoTypeList.value = data;
}

const submitForm = async (formEl: FormInstance | undefined) => {

  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    let result: ApiResult<any>;
    if (valid) {
      submitLoading.value = true;
      let params = {
        auditReason:formData.auditReason,
        auditState:parseInt(auditState.value),
        id:props.data?.id,
        leturer:formData.leturer,
        trainingTime:formData.date+" "+formData.time+':00'
      }

      console.log(params)

      result = await audit(params)



      // if (formData?.id) {
      //   result = await updateVideo(formData);
      // } else {
      //   result = await addVideo(formData);
      // }
      const { success, msg } = result;
      submitLoading.value = false;
      if (!success) {
        ElMessage.error(msg);
        return;
      }
      ElMessage.success("操作成功");
      closeDialog();
      emit("submit");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile);
  if (rawFile.type.split("/")[0] !== "video") {
    ElMessage.error("只能上传视频!");
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 500) {
    ElMessage.error("视频不能大于500M");
    return false;
  }
  return true;
};

const getGennerDate = () => {
    const today = dayjs();
    let dates = [];
    for (let i = 1; i <= 30; i++) {
      const date = today.add(i - 1, 'day').format('YYYY-MM-DD'); // i + 1 因为起始点是后两天
      dates.push({ label: date, value: date });
    }

    dateList.value = dates
    timeList.value = [
      { label: "09:00", value: "09:00" },
      { label: "10:00", value: "10:00" },
      { label: "11:00", value: "11:00" },
      { label: "15:00", value: "15:00" },
      { label: "16:00", value: "16:00" },
      { label: "17:00", value: "17:00" }
    ]
    
  }

const getUserList = async () => {
    const { success, data } = await selectMiniTranUsers({ })
    if (success) {
      userList.value = data
    }
  }

onMounted(async () => {
  await getSelectVideoList();
  getGennerDate()
  await getUserList()
});
watch(dialogVisible, (visible) => {
  Object.keys(formData).forEach((key: any) => {
    formData[key as keyof IForm] = visible ? props.data?.[key] || "" : "";
  });

  formData.date = props.data?.trainingTime?.substr(0,10)
  formData.time = props.data?.trainingTime?.substr(11,5)
  auditState.value ='2'
});

watch(auditState, (count, prevCount) => {
  if(count == '2'){
    rules.auditReason =  [{ required: false, message: "请输入", trigger: "blur" }]
  }else{
    rules.auditReason =  [{ required: true, message: "请输入", trigger: "blur" }]
  }
})
</script>

<style scoped lang="scss">
.footer {
  width: 100%;
  text-align: center;
  margin-top: 50px;
}
.upload-demo {
  width: 100%;
}
.videoWrap{
  border: 1px solid #999
}
.auditWrap{
  display: flex;
  justify-content: center;
  margin-bottom: 48px;
}
</style>
